define(function(require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    

    var scheduleUtil = require('oa/js/schedule/asset/utils/scheduleUtil.repeat');

    (function() {
        var me = scheduleUtil;

        var currentPageUserId = SESSION.user.id;

        //DISPLAY-SETTING
        var displaySettings = {
            userId: currentPageUserId,
            showTask: true,
            onlyShowUnfinishedTasks: true,
            scheduleTypes: '' //'' means all, -1 means none
        };
        var ds_cookie_prefix = 'displaysetting-';
        me.retriveDisplaySetting = function() {
            var currentId = currentPageUserId;
            var currentLoggedId = $.cookie(ds_cookie_prefix + 'currentLoggedId');

            if (currentId == currentLoggedId) {
                //return;
                for (key in displaySettings) {
                    var val = me.getDisplaySettingByCookie(key);
                    if (typeof val != 'undefined') {
                        displaySettings[key] = val;
                    }
                }
            } else {
                for (var key in displaySettings) {
                    $.removeCookie(ds_cookie_prefix + key); //if is new logged user, clean previous cookies
                }
                $.cookie(ds_cookie_prefix + 'currentLoggedId', currentId);
            }
        };
        me.getDisplaySettingByCookie = function(key) {
            var val = $.cookie(ds_cookie_prefix + key);
            if (typeof val != 'undefined') {
                if (val == 'true') val = true;
                if (val == 'false') val = false;
                if ($.isNumeric(val)) val = parseInt(val);
                return val;
            }
        };
        me.getDisplaySetting = function(key) {
            return displaySettings[key];
        };
        me.setDisplaySetting = function(key, val) {
            displaySettings[key] = val;
            $.cookie(ds_cookie_prefix + key, val);
        };

        me.loadUnAcceptedNum = function(data) {
            if (!data.data || !data.data.unacceptCount) {
                me.setUnAcceptedNum(0);
                return;
            }
            var notAcceptedNum = data.data.unacceptCount;
            if ($.isNumeric(notAcceptedNum)) {
                notAcceptedNum = parseInt(notAcceptedNum);
                me.setUnAcceptedNum(notAcceptedNum);
            }
        };
        me.setUnAcceptedNum = function(num) {
            if (num > 0) {
                $('.btn-unconfirm').html('未确认日程(' + num + ')').css('visibility', 'visible');
                $('.btn-unconfirm-split').css('visibility', 'visible');
            } else {
                $('.btn-unconfirm').css('visibility', 'hidden');
                $('.btn-unconfirm-split').css('visibility', 'hidden');
            }
        };

        // window.scheduleUtil.reRenderEvents = function(){
        //  // renderScheduleEvents(g_scheduleList);
        //  // renderTaskEvents(g_taskList);
        // }
        me.closeEditor = function() {
            $.closePopupLayer();
        };
        me.popupEditor = function(option) {
            if (typeof option == 'undefined') option = {};

            if (!option.startDate && !option.endDate) { //用户未指定
                var range = _getCreateRange();
                option.startDate = range.start.format('YYYY-MM-DD'),
                    option.startTime = range.start.format('HH:mm:ss'),
                    option.endDate = range.end.format('YYYY-MM-DD'),
                    option.endTime = range.end.format('HH:mm:ss')
            }

            var url = '/json/crm_func/get-crm-func.action';
            rk.post(url, {}).done(function (json) {
                if (json.status == 0) {
                    SESSION.func = json.data.permission.func;

                    var html = require.async('oa/tmpl/schedule/editor/template_calEventEditor.tpl', function(tmpl) {
                        SESSION.wanxue = WANXUE;
                        tmpl = rk.templateText(tmpl,{SESSION:SESSION});
                        rk.popup({
                            dragHandle: 'div.pop_head',
                            name: "myStaticPopup",
                            width: 485,
                            target: $(tmpl)
                        });

                        require.async('oa/js/schedule/asset/plus/eventEditorWindow', function() {
                            var elem = $('#popupLayer_myStaticPopup').find('[data-plugin="eventEditorWindow"]');
                            elem.eventEditorWindow(option);
                        });
                    });
                } else {
                    $.msg(rk.i18n('LOAD_ERROR'));
                }
            });
            /*var html = require.async('oa/tmpl/schedule/editor/template_calEventEditor.tpl', function(tmpl) {
                SESSION.wanxue = WANXUE;
                tmpl = rk.templateText(tmpl,{SESSION:SESSION});
                rk.popup({
                    dragHandle: 'div.pop_head',
                    name: "myStaticPopup",
                    width: 485,
                    target: $(tmpl)
                });

                require.async('oa/js/schedule/asset/plus/eventEditorWindow', function() {
                    var elem = $('#popupLayer_myStaticPopup').find('[data-plugin="eventEditorWindow"]');
                    elem.eventEditorWindow(option);
                });
            });*/

        };

        function _getCreateRange(millis) {
            var start = moment();
            if (typeof millis != 'undefined') {
                start = moment(millis - 0);
            }
            start.set('minutes', 0);
            start.set('second', 0);
            start.add(60, 'minutes');
            var end = moment(+start.toDate() + 30 * 60 * 1000);
            return {
                start: start,
                end: end
            }
        };
        me._getCreateRange = _getCreateRange;

        //COLOR
        var colorList;
        me.getInitColorList = function(data, callback) {
            if (data.data && data.data.salesParameterList && data.data.salesParameterList.length) colorList = data.data.salesParameterList;
        }
        me.fetchColorList = function(callback) {
            if (typeof callback == 'undefined') callback = function() {};
            if (colorList) {
                (callback)(colorList);
                return;
            }
            $.ajax({
                url: "/json/crm_schedule/color-type.action",
                dataType: 'json'
            }).success(function( /*PlainObject*/ data, /*String*/ textStatus, /*jqXHR*/ jqXHR) {
                if (data && data.data && data.data.salesParameter && data.data.salesParameter.length) {
                    colorList = data.data.salesParameter;
                    (callback)(colorList);
                } else {
                    colorList = null;
                }
            });
        }

        //BUSY
        function createBusy() {
            if ($('#calendar').find('>.schedule_busy').size() == 0) {
                $('#calendar').find('.fc-content').before('<div class="schedule_busy"><span class="loading"></span></div>');
            }
        }
        me.showBusy = function() {
            createBusy();
            $('#calendar').find('.fc-content').css('visibility', 'hidden');
            $('#calendar').find('.schedule_busy').show().beLoading();
            //$('#calendar').loadmask("加载中...");
        }
        me.hideBusy = function() {
            $('#calendar').find('.fc-content').css('visibility', '');
            $('#calendar').find('.schedule_busy').hide().unLoading();
            //$('#calendar').unloadmask();
        }

        var eventPool = {};
        me.bindEvent = function(ename, fn) {
            var fnlist = eventPool[ename];
            if (!fnlist) fnlist = [];
            fnlist.push(fn);
            eventPool[ename] = fnlist;
        }
        me.fireEvent = function(ename) {
            var fnlist = eventPool[ename];
            if (!fnlist) return;
            for (var i = 0, len = fnlist.length; i < len; i++) {
                (fnlist[i])();
            }
        }

        me.getViewName = function(view) {
                var viewName;
                switch (view) {
                    case 'day':
                        viewName = 'agendaDay';
                        break;
                    case 'month':
                        viewName = 'month';
                        break;
                    case 'week':
                        viewName = 'agendaWeek';
                        break;
                    default:
                        ;
                }
                return viewName;
            },
            me.getAliasName = function(view) {
                var aliasName;
                switch (view) {
                    case 'agendaDay':
                        aliasName = 'day';
                        break;
                    case 'month':
                        aliasName = 'month';
                        break;
                    case 'agendaWeek':
                        aliasName = 'week';
                        break;
                    default:
                        ;
                }
                return aliasName;
            }
            // //DEBUG
            // window.__help = function(id) {
            //     println('__checkevent(eventId)');
            //     println('__checkmom(miliseconds)');
            // }
            // window.__checkmom = function(num) {
            //     println(moment(num).format())
            // }
            // window.__checkevent = function(id) {
            //     id = id + '';
            //     var data = scheduleUtil.currentData;
            //     if (!data) return;
            //     var schList = data.data.schedules;
            //     for (var i = 0, len = schList.length; i < len; i++) {
            //         var sch = schList[i];
            //         if (sch.id == id) {
            //             var sm = moment(parseInt(sch.startDate));
            //             var em = moment(parseInt(sch.endDate));
            //             println(id + ':' + sm.format() + ' -> ' + em.format() + ',diff:' + em.diff(sm, 'hours') + 'h or ' + em.diff(sm, 'days') + 'd')
            //             println('  isAllDay:' + sch.isAllDay + ', isRecur:' + sch.isRecur + ',frq:' + sch.frequency + ', interval:' + sch.interval + ',diff:' + sch.end)
            //             println('  color id:' + sch.colorType.id + ', name:' + sch.colorType.name + ', color:' + sch.colorType.color)
            //             var ss = '';
            //             for (var s in sch) {
            //                 var v = sch[s];
            //                 if (typeof s != 'function') ss = ss + ',' + s + ':' + (v > 10000 ? moment(v).format() : v);
            //             }
            //             println(ss);
            //         }
            //     }
            //     $('div[event-id="' + id + '"]').css('border', '5px solid yellow');
            //     me._is_debug_mode = true;
            //     return id;
            // };


    })();

    return scheduleUtil;
});
